package o2o.task.sys;


import com.jinyou.utils.common.DateUtils;
import com.jinyou.utils.common.ValidateUtil;
import com.mongodb.BasicDBObject;
import o2o.config.dao.MongoDaoImpl;
import o2o.dao.PO.release.ReleaseInformationMongo;
import o2o.dao.PO.sys.SMSLog;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

// 用户登录日志记录
public class SmsLogUtils {

    private static List<SMSLog> smsLogList = new ArrayList<>();


    public static void addLog(String username, String code, Long sendTime, String smsKey) {
        if (ValidateUtil.isNull(username)) {
            return;
        }
        SMSLog loginLog = new SMSLog();
        loginLog.setPhone(username);
        loginLog.setSendTime(sendTime);
//        loginLog.setSendTimes(DateUtils.timeStampToDatetime(sendTime));
        loginLog.setCode(code);
        loginLog.setSysAppKey(smsKey);
        smsLogList.add(loginLog);
    }


    public static void exeLogReal() {
        if (!ValidateUtil.isAbsList(smsLogList)) {
            return;
        }
        List<SMSLog> list = new ArrayList<>(smsLogList);
        smsLogList.clear();

        if (ValidateUtil.isAbsList(list)) {
            for (int i = 0; i < list.size(); i++) {
                SMSLog loginLog = list.get(i);
                if (null == loginLog) {
                    continue;
                }

                String username = loginLog.getPhone();
                if (ValidateUtil.isNull(username)) {
                    continue;
                }

                Long LogTime = loginLog.getSendTime();
                if (ValidateUtil.isNotAbsLong(LogTime)) {
                    LogTime = DateUtils.getCurrTime();
                }


                BasicDBObject insert = new BasicDBObject();
                insert.append("phone", username);
                insert.append("sysAppKey", loginLog.getSysAppKey());
                insert.append("code", loginLog.getCode());
                insert.append("sendTimeStr", DateUtils.sdfDateTime.get().format(LogTime));
                insert.append("sendTime", LogTime);
                insert.append("saveTime", DateUtils.getCurrTime());
//                MongoDaoImpl.getInstance().update("sms_log", "user_sms_curr", query, update, true);
                MongoDaoImpl.getInstance().insert("sms_log", "user_sms", insert);
            }
        }


        // 自动删除1个月之前的
        Map<String, Object> query = new HashMap<>();
        query.put("saveTime", new BasicDBObject("$lt", DateUtils.getPreDaysOfTimestamp(45l)));
//        MongoDaoImpl.getInstance().delete("records_information", "release_00_sticky", query);
        MongoDaoImpl.getInstance().delete("sms_log", "user_sms", query);

    }


}
